<template>
  <div v-if="showPanel" class="knowledge-wrapper">
    <!-- 知识库面板 -->
    <div class="knowledge-panel">
      <div class="knowledge-header">
        <h3>知识库</h3>
        <button class="close-panel-btn" @click="closePanel">×</button>
      </div>
      
      <div class="knowledge-content">
        <button class="add-knowledge-btn" @click="openKnowledgeDialog">
          <span class="plus-icon">+</span>
          添加知识库
        </button>
        
        <div class="knowledge-list">
          <div 
            v-for="kb in knowledgeList" 
            :key="kb.id"
            :class="['knowledge-item', { active: selectedKnowledge?.id === kb.id }]"
            @click="selectKnowledge(kb)"
          >
            <span class="knowledge-icon">📚</span>
            <span class="knowledge-name">{{ kb.name }}</span>
            <span class="knowledge-count">{{ kb.files.length }}个文件</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件列表面板 -->
    <div v-if="showFilePanel && selectedKnowledge" class="file-panel">
      <div class="file-header">
        <h3>{{ selectedKnowledge.name }}</h3>
        <button class="close-panel-btn" @click="closeFilePanel">×</button>
      </div>
      
      <div class="file-content">
        <div class="file-info">
          <div class="info-item">
            <span class="info-label">chunking_strategy 参数:</span>
            <span class="info-value">{{ selectedKnowledge.chunkingStrategy === 'auto' ? '自动' : '手动' }}</span>
          </div>
          <div class="chunking-params">
            <span class="param-item">chunk_size: {{ selectedKnowledge.chunkSize || 800 }}</span>
            <span class="param-item">chunk_overlap_tokens: {{ selectedKnowledge.chunkOverlap || 400 }}</span>
          </div>
        </div>
        
        <div class="file-list-container">
          <div 
            v-for="file in selectedKnowledge.files" 
            :key="file.name"
            class="file-item-display"
          >
            <span class="file-icon-display">📄</span>
            <span class="file-name-display">{{ file.name }}</span>
            <button class="remove-file-btn" @click="removeFileFromKnowledge(file)">×</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 知识库合集对话框 -->
    <div v-if="showKnowledgeDialog" class="dialog-overlay" @click="closeKnowledgeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>新建知识库</h3>
          <button class="close-btn" @click="closeKnowledgeDialog">×</button>
        </div>
        
        <div class="dialog-body">
          <div class="form-group">
            <label>知识库名称 *</label>
            <input v-model="knowledgeForm.name" type="text" placeholder="请输入知识库名称" class="form-input">
          </div>
          
          <div class="form-group">
            <label>上传文件 *</label>
            <div class="upload-section">
              <div class="upload-area" @click="triggerFileUpload" @drop="handleDrop" @dragover="handleDragOver">
                <input ref="fileInput" type="file" multiple accept=".pdf,.doc,.docx,.txt,.md,.xls,.xlsx,.csv"
                       @change="handleFileSelect" style="display: none;">
                <div class="upload-icon">☁️</div>
                <div class="upload-text">点击或拖拽文件支持文件夹选择上传</div>
                <div class="upload-subtitle">支持上传docx, 支持PDF、Word、PPT、Markdown等格式文档</div>
              </div>
              
              <div v-if="selectedFiles.length > 0" class="file-list">
                <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
                  <span class="file-icon">📄</span>
                  <span class="file-name">{{ file.name }}</span>
                  <button class="remove-file" @click="removeFile(index)">×</button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="form-group">
            <label>chunking_strategy 参数</label>
            <div class="radio-group">
              <label class="radio-item">
                <input type="radio" v-model="knowledgeForm.chunkingStrategy" value="auto" name="chunking">
                <span class="radio-label">自动</span>
              </label>
              <label class="radio-item">
                <input type="radio" v-model="knowledgeForm.chunkingStrategy" value="manual" name="chunking">
                <span class="radio-label">手动</span>
              </label>
            </div>
          </div>
          
          <!-- 上传进度显示 -->
          <div v-if="isUploading" class="upload-progress-section">
            <div class="progress-header">
              <span>{{ uploadStatus }}</span>
              <span>{{ Math.floor(uploadProgress) }}%</span>
            </div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
            </div>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeKnowledgeDialog" :disabled="isUploading">取消</button>
          <button class="submit-btn" @click="submitKnowledge" :disabled="!canSubmit">
            <span v-if="isUploading">⏳ 上传中...</span>
            <span v-else>新建知识库</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { uploadDocuments } from '@/api/chat.js'
import { ElMessage, ElNotification } from 'element-plus'

// Props
const props = defineProps({
  showPanel: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['close', 'panel-state-change'])

// 响应式数据
const showFilePanel = ref(false)
const knowledgeList = ref([])
const selectedKnowledge = ref(null)
const showKnowledgeDialog = ref(false)
const fileInput = ref(null)
const selectedFiles = ref([])
const knowledgeForm = reactive({
  name: '',
  chunkingStrategy: 'auto'
})
const isUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')

// 计算属性
const canSubmit = computed(() => {
  return knowledgeForm.name.trim() && selectedFiles.value.length > 0 && !isUploading.value
})

// 方法
const closePanel = () => {
  showFilePanel.value = false
  selectedKnowledge.value = null
  emit('close')
}

const closeFilePanel = () => {
  showFilePanel.value = false
  selectedKnowledge.value = null
  emitPanelState()
}

const selectKnowledge = (knowledge) => {
  selectedKnowledge.value = knowledge
  showFilePanel.value = true
  emitPanelState()
}

const removeFileFromKnowledge = (fileToRemove) => {
  if (selectedKnowledge.value) {
    const index = selectedKnowledge.value.files.findIndex(f => f.name === fileToRemove.name)
    if (index > -1) {
      selectedKnowledge.value.files.splice(index, 1)
    }
  }
}

const openKnowledgeDialog = () => {
  showKnowledgeDialog.value = true
}

const closeKnowledgeDialog = () => {
  showKnowledgeDialog.value = false
  knowledgeForm.name = ''
  knowledgeForm.chunkingStrategy = 'auto'
  selectedFiles.value = []
  isUploading.value = false
  uploadProgress.value = 0
  uploadStatus.value = ''
}

const triggerFileUpload = () => {
  fileInput.value.click()
}

const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  selectedFiles.value.push(...files)
}

const handleDrop = (event) => {
  event.preventDefault()
  const files = Array.from(event.dataTransfer.files)
  selectedFiles.value.push(...files)
}

const handleDragOver = (event) => {
  event.preventDefault()
}

const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

const submitKnowledge = async () => {
  if (!canSubmit.value || isUploading.value) return
  
  isUploading.value = true
  uploadProgress.value = 0
  uploadStatus.value = '准备上传...'
  
  try {
    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += Math.random() * 10
        uploadStatus.value = `上传中... ${Math.floor(uploadProgress.value)}%`
      }
    }, 300)
    
    // 调用上传接口
    const result = await uploadDocuments({
      files: selectedFiles.value,
      splitter_type: knowledgeForm.chunkingStrategy === 'auto' ? 'q&a' : 'recursive',
      chunk_sizes: '2048',
      collection_name: knowledgeForm.name
    })

    clearInterval(progressInterval)

    if (result.code === 200) {
      uploadProgress.value = 100
      uploadStatus.value = '上传完成！'
      ElMessage({
        message: result.msg,
        type: 'success',
        duration: 2000
      })
      if (result.data.success_files && result.data.success_files.length > 0) {
        const successDetails = result.data.success_files.map(file => 
          `• ${file.filename} (${file.nodes_count}个块, ${file.splitter_type}模式)`
        ).join('\n')
        
        ElNotification({
          title: '文件处理完成',
          message: `知识库: ${result.data.collection_name}\n总计生成: ${result.data.total_chunks}个文档块\n\n成功文件:\n${successDetails}`,
          type: 'success',
          duration: 6000,
          position: 'top-right'
        })
      }
      if (result.data.failed_files && result.data.failed_files.length > 0) {
        ElNotification({
          title: '部分文件处理失败',
          message: `失败文件: ${result.data.failed_files.join(', ')}`,
          type: 'warning',
          duration: 5000,
          position: 'top-right'
        })
      }
      const newKnowledge = {
        id: Date.now(),
        name: result.data.collection_name,
        files: [...selectedFiles.value],
        chunkingStrategy: knowledgeForm.chunkingStrategy,
        chunkSize: 800,
        chunkOverlap: 400,
        createdAt: new Date(),
        totalChunks: result.data.total_chunks,
        successFiles: result.data.success_files,
        failedFiles: result.data.failed_files
      }
      knowledgeList.value.push(newKnowledge)
      setTimeout(() => {
        closeKnowledgeDialog()
      }, 2000)
      
    } else {
      uploadStatus.value = `上传失败: ${result.msg}`
      ElMessage({
        message: `上传失败: ${result.msg}`,
        type: 'error',
        duration: 5000
      })
    }
    
  } catch (error) {
    uploadStatus.value = `上传失败: ${error.message}`
    ElMessage({
      message: `上传异常: ${error.message}`,
      type: 'error',
      duration: 5000
    })
  } finally {
    isUploading.value = false
  }
}

const emitPanelState = () => {
  emit('panel-state-change', {
    showKnowledgePanel: props.showPanel,
    showFilePanel: showFilePanel.value
  })
}

// 监听面板状态变化
import { watch } from 'vue'
watch(() => props.showPanel, (newVal) => {
  if (!newVal) {
    showFilePanel.value = false
    selectedKnowledge.value = null
  }
  emitPanelState()
})

watch(showFilePanel, () => {
  emitPanelState()
})
</script>

<style scoped>
.knowledge-wrapper {
  display: flex;
  flex: 1;
  height: 100vh;
}

/* 知识库面板样式 */
.knowledge-panel {
  width: 20%;
  min-width: 280px;
  background: rgba(15, 30, 45, 0.8);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 2;
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.knowledge-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.close-panel-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 20px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-panel-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.knowledge-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.add-knowledge-btn {
  width: 100%;
  padding: 12px;
  background: #00d4aa;
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.add-knowledge-btn:hover {
  background: #00c199;
  transform: translateY(-1px);
}

.knowledge-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.knowledge-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.knowledge-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.knowledge-item.active {
  background: rgba(0, 212, 170, 0.2);
  border-color: rgba(0, 212, 170, 0.3);
}

.knowledge-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.knowledge-name {
  flex: 1;
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.knowledge-count {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

/* 文件面板样式 */
.file-panel {
  width: 80%;
  background: rgba(15, 30, 45, 0.8);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
}

.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.file-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.file-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.file-info {
  margin-bottom: 24px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.info-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.info-value {
  color: #00d4aa;
  font-size: 14px;
  font-weight: 500;
}

.chunking-params {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.param-item {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.file-list-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-item-display {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.file-icon-display {
  font-size: 16px;
  flex-shrink: 0;
}

.file-name-display {
  flex: 1;
  color: white;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.remove-file-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 16px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.remove-file-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ff6b6b;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.dialog-content {
  background: #1a2b3d;
  border-radius: 12px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.dialog-header h3 {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.dialog-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  color: white;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  color: white;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #00d4aa;
  background: rgba(255, 255, 255, 0.08);
}

.form-input::placeholder {
  color: rgba(255, 255, 255, 0.4);
}

.upload-section {
  width: 100%;
}

.upload-area {
  border: 2px dashed rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.02);
}

.upload-area:hover {
  border-color: #00d4aa;
  background: rgba(0, 212, 170, 0.05);
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 16px;
}

.upload-text {
  color: white;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.upload-subtitle {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.file-list {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  margin-bottom: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.file-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.file-name {
  flex: 1;
  color: white;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.remove-file {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.remove-file:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ff6b6b;
}

.radio-group {
  display: flex;
  gap: 24px;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: white;
  font-size: 14px;
}

.radio-item input[type="radio"] {
  width: 16px;
  height: 16px;
  accent-color: #00d4aa;
}

/* 上传进度样式 */
.upload-progress-section {
  margin-top: 20px;
  padding: 16px;
  background: rgba(0, 212, 170, 0.1);
  border: 1px solid rgba(0, 212, 170, 0.2);
  border-radius: 8px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  color: white;
  font-size: 14px;
}

.progress-bar {
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4aa, #4dabf7);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.cancel-btn,
.submit-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.submit-btn {
  background: #00d4aa;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #00c199;
  transform: translateY(-1px);
}

.submit-btn:disabled {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.3);
  cursor: not-allowed;
  transform: none;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .knowledge-wrapper {
    flex-direction: column;
  }
  
  .knowledge-panel {
    width: 100%;
    min-width: auto;
    height: 40%;
  }
  
  .file-panel {
    width: 100%;
    height: 60%;
  }
}
</style> 